<template>
	<el-card>
		<el-form
			ref="publishformRef"
			:model="publishform"
			label-width="120px"
			label-position="top"
		>
			<el-form-item
				label="博客标题"
				prop="name"
				:rules="[
					{
						required: true,
						message: '博客标题不能为空',
						trigger: 'blur',
					},
				]"
			>
				<el-input
					v-model="publishform.name"
					placeholder="请输入博客标题"
				/>
			</el-form-item>

			<el-form-item
				label="博客标签"
				prop="tags"
				:rules="[
					{
						required: true,
						message: '博客标签不能为空',
						trigger: 'blur',
					},
				]"
			>
				<el-tag
					v-for="tag in publishform.tags"
					:key="tag"
					class="mx-1"
					closable
					:disable-transitions="true"
					@close="handleClose(tag)"
				>
					{{ tag }}
				</el-tag>
				<el-input
					v-if="taginputVisible"
					ref="InputRef"
					v-model="inputtagValue"
					class="ml-1 w-120"
					size="small"
					@keyup.enter="handleInputConfirm"
					@blur="handleInputConfirm"
				/>
				<el-button
					v-if="tagbuttonVisible"
					class="w-120 ml-1"
					size="small"
					@click="showInput"
				>
					+ 增加标签
				</el-button>
			</el-form-item>

			<el-form-item
				label="博客封面"
				prop="image"
				:rules="[
					{
						required: true,
						message: '博客封面不能为空',
						trigger: 'change',
					},
				]"
			>
				<el-upload
					class="avatar-uploader"
					action=""
					:http-request="uploadimg"
					:show-file-list="false"
					:before-upload="beforeAvatarUpload"
				>
					<el-image
						v-if="publishform.image"
						:src="publishform.image"
						class="avater"
						fit="cover"
					/>
					<el-icon v-else class="avatar-uploader-icon"
						><Plus
					/></el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item
				label="博客内容"
				prop="content"
				:rules="[
					{
						required: true,
						message: '博客内容不能为空',
						trigger: 'change',
					},
				]"
			>
				<div class="publish">
					<Toolbar
						style="border-bottom: 1px solid #ccc"
						:editor="editorRef"
						:defaultConfig="toolbarConfig"
						:mode="mode"
					/>
					<Editor
						style="height: 500px; overflow-y: hidden"
						v-model="publishform.content"
						:defaultConfig="editorConfig"
						:mode="mode"
						@onCreated="handleCreated"
					/>
				</div>
			</el-form-item>
			<el-button
				class="btn"
				type="primary"
				size="small"
				@click="publish()"
				>提交</el-button
			>
		</el-form>
	</el-card>
</template>

<script>
import "@wangeditor/editor/dist/css/style.css";
import {
	ref,
	shallowRef,
	onBeforeUnmount,
	reactive,
	toRefs,
	nextTick,
	watchEffect,
	onMounted,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { DomEditor } from "@wangeditor/editor";
import { ElMessage } from "element-plus";
import { updateimg, deleteimg } from "@/network/postimg";
import {
	apipublishblog,
	apibeforeupdateblog,
	apiupdatelog,
} from "@/network/blog";
import { useRoute } from "vue-router";

export default {
	name: "Publish",
	components: { Editor, Toolbar },
	setup() {
		// form ref
		const publishformRef = ref(null);
		// tags ref
		const InputRef = ref(null);
		// route
		const route = useRoute();
		var _id = route.query._id;

		// 编辑器实例，必须用 shallowRef
		const editorRef = shallowRef();

		// 数据模型
		const data = reactive({
			// 增加标签需要的数据
			taginputVisible: false,
			tagbuttonVisible: true,
			inputtagValue: "",
			publishform: {
				name: "",
				tags: [],
				image: "",
				content: "",
			},
			// 上传了的图片，或初始化时带有的图片
			postcontentimg: [],
		});

		onMounted(() => {
			if (_id) {
				apibeforeupdateblog({ _id }).then((res) => {
					console.log(res);
					data.publishform._id = res.data._id;
					data.publishform.name = res.data.name;
					data.publishform.tags = res.data.tags;
					data.publishform.image = res.data.image;
					data.publishform.content = res.data.content;
					// 获取content中的图片
					const hasimg = res.data.content.match(
						/(?<=img src=")http.*?(?=")/gi
					);
					if (hasimg) {
						data.postcontentimg.push(...hasimg);
					}
				});
			}
		});

		const toolbarConfig = {
			excludeKeys: ["uploadVideo"],
		};
		const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} };
		editorConfig.MENU_CONF["uploadImage"] = {
			// 上传图片的配置
			// 服务端地址
			server: "/api/img/updateimg",
			// form-data fieldName ，默认值 'wangeditor-uploaded-image'
			fieldName: "file",
			// 单个文件的最大体积限制，默认为 2M
			// maxFileSize: 2 * 1024 * 1024, // 2M
			// 最多可上传几个文件，默认为 100
			// maxNumberOfFiles: 10,
			// 单个文件上传成功之后
			onSuccess(file, res) {
				console.log(`${file.name} 上传成功`, res);
				data.postcontentimg.push(res.data[0].url);
			},
		};

		// 组件销毁时，也及时销毁编辑器
		onBeforeUnmount(() => {
			const editor = editorRef.value;
			if (editor == null) return;
			editor.destroy();
		});

		const handleCreated = (editor) => {
			// 记录 editor 实例，重要！
			editorRef.value = editor;
		};

		// 提交
		const publish = (formEl = publishformRef.value) => {
			console.log(data.publishform);

			if (!formEl) return;
			formEl.validate((valid) => {
				if (valid) {
					if (_id) {
						apiupdatelog(data.publishform).then((res) => {
							updatatitle(res);
						});
					} else {
						apipublishblog(data.publishform).then((res) => {
							updatatitle(res);
						});
					}
					// 实际内容中的图片
					if (data.postcontentimg) {
						var getcontetntimg =
							editorRef.value.getElemsByType("image");
						var deletepostimg = data.postcontentimg.filter(
							(item) => {
								return !getcontetntimg.some((i) => {
									return i.src === item;
								});
							}
						);
						deleteimg(deletepostimg);
					}
				}
			});
		};

		const updatatitle = (res) => {
			if (res.status == 200) {
				ElMessage.success("发布成功");
				data.publishform = {
					name: "",
					tags: [],
					image: "",
					content: "",
				};
			}
		};

		// 删除tag
		const handleClose = (tag) => {
			data.publishform.tags.splice(data.publishform.tags.indexOf(tag), 1);
		};

		// tag输入框
		const handleInputConfirm = () => {
			if (data.inputtagValue) {
				data.publishform.tags.push(data.inputtagValue);
			}
			data.taginputVisible = false;
			data.inputtagValue = "";
		};

		// 点击增加标签按钮
		const showInput = () => {
			data.taginputVisible = true;
			nextTick(() => {
				InputRef.value.input.focus();
			});
		};

		// 监听
		watchEffect(() => {
			data.tagbuttonVisible =
				!data.taginputVisible && data.publishform.tags.length < 5;
		});

		// 封面上传（覆盖默认的 Xhr 行为，允许自行实现上传文件的请求）
		const uploadimg = (param) => {
			if (data.publishform.image) {
				// 删除上一张图片
				let oldimage = [];
				oldimage.push(data.publishform.image);
				deleteimg(oldimage);
			}

			var formData = new FormData();
			formData.append("file", param.file);
			updateimg(formData)
				.then((res) => {
					if (res.status == 200) {
						data.publishform.image = res.data.data[0].url;
						ElMessage.success("上传成功");
					}
				})
				.catch((err) => {
					ElMessage.error("上传图片失败！");
				});
		};

		// 封面上传文件之前的钩子
		const beforeAvatarUpload = (rawFile) => {
			var imgtype = /^image\/*/.test(rawFile.type);
			if (!imgtype) {
				ElMessage.error("请上传图片类型！");
				return false;
			} else if (rawFile.size / 1024 / 1024 > 2) {
				ElMessage.error("图片大小不能超过5M!");
				return false;
			}
			return true;
		};

		return {
			...toRefs(data),
			publishformRef,
			InputRef,
			editorRef,
			mode: "default",
			toolbarConfig,
			editorConfig,
			handleCreated,
			publish,
			handleClose,
			handleInputConfirm,
			showInput,
			uploadimg,
			beforeAvatarUpload,
		};
	},
};
</script>

<style lang="scss" scoped>
.publish {
	border: 1px solid #ccc;
}
.btn {
	margin-top: 10px;
}
.mx-1 {
	margin-right: 10px;
}
.w-120 {
	width: 120px;
	height: 30px;
}

.avatar-uploader {
	width: 322px;
	height: 200px;
	border: 1px dashed #999;
	border-radius: 5px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

:deep(.avater > img) {
	display: block;
	width: 322px;
	height: 200px;
	border-radius: 5px;
}
.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 322px;
	height: 200px;
	text-align: center;
}
</style>
